<template>
  <Dialog
    :title="title"
    :model-value="visible"
    width="1000px"
    max-height="800px"
    :before-close="closeForm"
  >
    <Form
      :schema="schema"
      :model="role"
      @register="formRegister"
      label-width="120px"
      :isCol="false"
      :rules="rules"
    />
    <ContentWrap title="权限目录" v-if="!role.IsAdmin" style="margin-top: 10px">
      <el-row style="width: 100%">
        <el-col :span="8">
          <div style="width: 100%; height: 350px; overflow-y: auto">
            <el-tree
              ref="powerTree"
              :data="trees"
              :default-expand-all="true"
              :highlight-current="true"
              :expand-on-click-node="false"
              style="width: 100%"
              :show-checkbox="true"
              :check-on-click-node="false"
              :check-on-click-leaf="false"
              :default-checked-keys="chioseKeys"
              :check-strictly="false"
              node-key="key"
              @node-click="chiosePower"
              @check-change="checkChange"
            >
              <template #default="{ node, data }">
                <div class="slot-t-node">
                  <Icon
                    v-if="data.style && data.style.icon"
                    :icon="data.style.icon"
                    :color="data.style.color"
                    :style="{ marginRight: '5px' }"
                  />
                  <span>{{ node.label }}</span>
                </div>
              </template>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="16">
          <ContentWrap :title="pTitle">
            <Table
              :data="powers"
              v-model:selectKey="selectKeys"
              row-key="Id"
              :check-is-select="checkIsChiose"
              :is-select="true"
              :is-multiple="true"
              :columns="columns"
              @change="
                () => {
                  loadPower(chioseId)
                }
              "
              @selected="
                (c) => {
                  isSet = true
                }
              "
            />
          </ContentWrap>
        </el-col>
      </el-row>
    </ContentWrap>
    <template #footer>
      <el-space>
        <BaseButton type="primary" @click="save">保存</BaseButton>
        <BaseButton @click="resetForm">重置</BaseButton>
      </el-space>
    </template>
  </Dialog>
</template>

<script>
import { GetTrees } from '@/api/role/power'
import * as roleApi from '@/api/role/role'
import { GetEnables } from '@/api/role/opPower'
import { Set } from '@/api/role/rolePower'
import { Dialog } from '@/components/Dialog'
import { Form } from '@/components/Form'
import { Table } from '@/components/Table'
import { useForm } from '@/hooks/web/useForm'
const { formRegister, formMethods } = useForm()
export default {
  components: {
    Dialog,
    Form,
    Table
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: String,
      default: null
    },
    comId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      title: '新增角色',
      powers: [],
      pTitle: '操作权限列表',
      isSet: false,
      schema: [
        {
          field: 'RoleName',
          label: '角色名称',
          component: 'Input',
          componentProps: {
            maxlength: 50,
            placeholder: '角色名称'
          }
        },
        {
          field: 'IsAdmin',
          label: '是否为管理员',
          component: 'Switch',
          componentProps: {}
        },
        {
          field: 'Remark',
          label: '备注',
          component: 'Input',
          componentProps: {
            maxlength: 255,
            type: 'textarea',
            placeholder: '备注'
          }
        }
      ],
      columns: [
        {
          field: 'OperateName',
          label: '权限名',
          align: 'center',
          minWidth: 150
        },
        {
          field: 'Show',
          label: '说明',
          align: 'left',
          minWidth: 150
        }
      ],
      role: {},
      trees: [],
      source: null,
      chioseKeys: [],
      selectKeys: [],
      powerId: null,
      chioseId: null,
      rules: {
        RoleName: [
          {
            required: true,
            message: '角色名不能为空！',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.loadTrees()
  },
  methods: {
    formRegister,
    checkIsChiose() {
      if (this.chioseId != null && this.chioseKeys.includes(this.chioseId)) {
        return true
      }
      return false
    },
    async saveOperPower(chioseId, keys) {
      await Set(this.roleId, chioseId, keys)
      this.$message({
        message: '保存成功!',
        type: 'success'
      })
    },
    async loadTrees() {
      const list = await GetTrees({
        IsEnable: true
      })
      this.trees = list.map((c) => {
        const t = {
          key: 'sys_' + c.SubSysId,
          type: 'isSubSystem',
          label: c.SubSysName,
          style: {
            icon: 'ep:home-filled',
            color: '#f56c6c'
          }
        }
        t.children = this.getPowers(c.Powers)
        return t
      })
    },
    chiosePower(data) {
      if (data.type === 0 && this.chioseId !== data.key) {
        if (this.chioseId != null && this.isSet) {
          this.saveOperPower(this.chioseId, this.selectKeys.concat())
        }
        this.isSet = false
        this.selectKeys = []
        this.chioseId = data.key
        this.pTitle = data.label + '操作权限列表'
        this.loadPower(data.key)
      }
    },
    checkChange(data, checked) {
      if (data.type === 'isSubSystem') {
        return
      }
      const index = this.powerId.findIndex((c) => c === data.key)
      if (checked) {
        if (index !== -1) {
          return
        }
        this.powerId.push(data.key)
      } else if (index !== -1) {
        this.powerId.splice(index, 1)
      }
    },
    getPowers(list) {
      return list.map((c) => {
        const t = {
          key: c.Id,
          type: c.PowerType,
          label: c.Name
        }
        if (c.PowerType === 1) {
          t.style = {
            icon: 'ep:folder',
            color: '#409eff'
          }
        } else if (c.PowerType === 0) {
          t.style = {
            icon: 'ep:document',
            color: '#000'
          }
        }
        if (c.Children && c.Children.length !== 0) {
          t.children = this.getPowers(c.Children)
        }
        return t
      })
    },
    async save() {
      if (this.chioseId != null && this.isSet) {
        this.saveOperPower(this.chioseId, this.selectKeys.concat())
      }
      const data = await formMethods.validate()
      if (data == null) {
        return
      } else if (this.roleId) {
        this.setRole(data)
      } else {
        this.setRole(data)
      }
    },
    async setRole(data) {
      data.PowerId = this.powerId
      await roleApi.set(this.roleId, data)
      this.$message({
        message: '更新成功!',
        type: 'success'
      })
      this.closeForm(true)
    },
    async addRole(data) {
      data.PowerId = this.powerId
      await roleApi.add(data)
      this.$message({
        message: '添加成功!',
        type: 'success'
      })
      this.closeForm(true)
    },
    async loadPower(powerId) {
      const res = await GetEnables(powerId, this.roleId)
      if (res == null) {
        this.powers = []
        this.selectKeys = []
        return
      }
      this.powers = res.Powers == null ? [] : res.Powers
      this.selectKeys = res.Selected == null ? [] : res.Selected
    },
    async reset() {
      this.chioseId = null
      if (this.roleId == null) {
        this.title = '新增角色'
        this.role = {
          IsAdmin: false
        }
        this.powerId = []
        this.chioseKeys = []
        this.source = {}
        this.$refs.powerTree.setCheckedKeys([], false)
      } else {
        const res = await roleApi.get(this.roleId)
        this.title = '编辑角色：' + res.RoleName
        if (res.PowerId == null) {
          res.PowerId = []
        }
        this.role = res
        this.source = res
        this.powerId = res.PowerId
        this.chioseKeys = res.PowerId
        if (!res.IsAdmin) {
          this.$refs.powerTree.setCheckedKeys(this.chioseKeys, false)
        }
      }
      formMethods.setValues(this.role)
    },
    closeForm(isRefresh) {
      if (isRefresh == null) {
        isRefresh = false
      }
      this.$emit('update:visible', false)
      this.$emit('close', isRefresh)
    },
    resetForm() {
      if (this.roleId == null) {
        this.role = {
          IsAdmin: false
        }
        this.powerId = []
        this.chioseKeys = []
        this.selectKeys = []
        this.$refs.powerTree.setCheckedKeys([], false)
      } else {
        this.role = this.source
        this.powerId = this.role.PowerId
        this.chioseKeys = this.role.PowerId
        this.selectKeys = []
        if (!this.role.IsAdmin) {
          this.$refs.powerTree.setCheckedKeys(this.chioseKeys, false)
        }
      }
      formMethods.setValues(this.role)
    }
  }
}
</script>
